#!/usr/bin/python3
# -*- coding: utf-8 -*-

from flask import Flask
from .config import config
from .utils.id_generator import IdGeneratorSingleton
import redis
import os
import sqlite3
from app.utils.sqlalchemy_utils import init_sqlalchemy

def create_app(config_name='default'):
    """
    应用工厂函数，创建并配置Flask应用实例
    
    Args:
        config_name: 配置名称，默认为'default'
        
    Returns:
        配置好的Flask应用实例
    """
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 初始化数据库
    with app.app_context():
        init_db(app)
    
    # 初始化Redis (使用单例模式)
    init_redis(app)
    
    # 初始化ID生成器
    init_id_generator(app)
    
    # 注册蓝图/路由
    register_blueprints(app)
    
    return app

def init_db(app):
    """
    初始化SQLite数据库
    
    Args:
        app: Flask应用实例
    """
    # 初始化SQLAlchemy
    init_sqlalchemy(app)
    
    # 以下是原有的SQLite初始化代码
    db_path = app.config['DB_PATH']
    db_exists = os.path.exists(db_path)
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    if not db_exists:
        print(f"创建新数据库: {db_path}")
        
        # 创建users表
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id TEXT PRIMARY KEY,
            user_id TEXT UNIQUE NOT NULL,
            username TEXT UNIQUE NOT NULL,
            password TEXT NOT NULL,
            email TEXT UNIQUE,
            name TEXT,
            age INTEGER,
            gender TEXT,
            address TEXT,
            phone TEXT,
            birthday TEXT,
            company TEXT,
            job TEXT,
            website TEXT,
            token TEXT,
            created_time TEXT,
            updated_time TEXT
        )
        ''')
        
        # 创建默认的admin用户
        # 使用UUID生成器为默认用户生成id
        from .utils.id_generator import UuidGenerator
        uuid_gen = UuidGenerator()
        admin_id = uuid_gen.format_id_no_hyphen()
        
        cursor.execute('''
        INSERT INTO users (id, user_id, username, password, email, name, created_time, updated_time)
        VALUES (?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
        ''', (admin_id, 'ADMIN-001', 'admin', 'admin123', 'admin@example.com', 'Administrator'))
        
        conn.commit()
    else:
        # 检查并更新现有表结构 - 如果从INTEGER自增主键迁移到TEXT类型的UUID
        try:
            # 检查id字段类型
            cursor.execute("PRAGMA table_info(users)")
            columns = cursor.fetchall()
            id_column = next((col for col in columns if col[1] == 'id'), None)
            
            # 如果id字段类型是INTEGER，需要迁移到TEXT
            if id_column and id_column[2] == 'INTEGER':
                print("迁移数据库: 将users表的id字段从INTEGER更改为TEXT...")
                
                # 创建临时表
                cursor.execute('''
                CREATE TABLE users_temp (
                    id TEXT PRIMARY KEY,
                    user_id TEXT UNIQUE NOT NULL,
                    username TEXT UNIQUE NOT NULL,
                    password TEXT NOT NULL,
                    email TEXT UNIQUE,
                    name TEXT,
                    age INTEGER,
                    gender TEXT,
                    address TEXT,
                    phone TEXT,
                    birthday TEXT,
                    company TEXT,
                    job TEXT,
                    website TEXT,
                    token TEXT,
                    created_time TEXT,
                    updated_time TEXT
                )
                ''')
                
                # 导入UUID生成器
                from .utils.id_generator import UuidGenerator
                uuid_gen = UuidGenerator()
                
                # 迁移数据
                cursor.execute("SELECT * FROM users")
                rows = cursor.fetchall()
                for row in rows:
                    # 为每个用户生成一个新的UUID作为id
                    new_id = uuid_gen.format_id_no_hyphen()
                    
                    # 构建新的插入语句
                    columns = [desc[0] for desc in cursor.description]
                    values = list(row)
                    values[columns.index('id')] = new_id
                    
                    # 插入数据到临时表
                    placeholders = ", ".join(["?"] * len(values))
                    insert_sql = f"INSERT INTO users_temp VALUES ({placeholders})"
                    cursor.execute(insert_sql, values)
                
                # 删除原表并重命名临时表
                cursor.execute("DROP TABLE users")
                cursor.execute("ALTER TABLE users_temp RENAME TO users")
                
                conn.commit()
                print("数据库迁移完成: users表的id字段现在是TEXT类型")
        except Exception as e:
            conn.rollback()
            print(f"数据库迁移失败: {str(e)}")
    
    conn.close()

class RedisSingleton:
    """Redis连接单例类"""
    _instance = None
    
    @classmethod
    def get_instance(cls, app=None):
        """获取Redis实例（单例模式）"""
        if cls._instance is None and app is not None:
            cls._instance = redis.Redis(
                host=app.config['REDIS_HOST'],
                port=app.config['REDIS_PORT'],
                password=app.config['REDIS_PASSWORD'],
                decode_responses=True
            )
            # 测试连接
            try:
                cls._instance.ping()
                print("成功连接到Redis服务器")
            except redis.ConnectionError:
                print("无法连接到Redis服务器，请检查连接信息")
                cls._instance = None
        
        return cls._instance

def init_redis(app):
    """初始化Redis连接"""
    RedisSingleton.get_instance(app)

def init_id_generator(app):
    """初始化ID生成器
    
    设置ID生成器类型，根据配置选择使用雪花算法或UUID
    
    Args:
        app: Flask应用实例
    """
    generator_type = app.config.get('ID_GENERATOR_TYPE', 'uuid')
    print(f"ID生成器类型: {generator_type}")
    
    # 设置ID生成器类型
    IdGeneratorSingleton.set_generator_type(generator_type)
    
    # 如果使用UUID，可以设置前缀
    if generator_type == 'uuid' and app.config.get('ID_PREFIX'):
        # 初始化一个实例以设置前缀
        IdGeneratorSingleton.get_instance(prefix=app.config.get('ID_PREFIX'))
    
    # 测试ID生成
    id_generator = IdGeneratorSingleton.get_instance()
    test_id = id_generator.format_id()
    print(f"测试生成ID: {test_id}")

def register_blueprints(app):
    """注册蓝图"""
    from .routes.auth_routes import auth_bp
    from .routes.user_routes import user_bp
    from .routes.service_routes import service_bp
    from .routes import print_registered_routes
    
    app.register_blueprint(auth_bp)
    app.register_blueprint(user_bp)
    app.register_blueprint(service_bp)
    
    # 打印所有已注册的路由，帮助调试
    print_registered_routes(app)
